package models

import (
	"context"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type MsgBasic struct {
	Data       string `bson:"data" json:"data"`
	CreatedAt  int64  `bson:"created_at" json:"created_at"`
	UpdateAt   int64  `bson:"updated_at" json:"updated_at"`
	UserId     string `bson:"user_id" json:"user_id"`         //发送者
	RoomId     string `bson:"room_id" json:"room_id"`         //接受者
	Type       int    `bson:"type" json:"type"`               //发送类型  1私聊  2群聊  3心跳
	Media      int    `bson:"media" json:"media"`             //消息类型  1文字 2表情包 3语音 4图片 /表情包
	Content    string `bson:"content" json:"content"`         //消息内容
	CreateTime int64  `bson:"create_time" json:"create_time"` //创建时间
	Icon       string `bson:"icon"  json:"icon"`
	Url        string `bson:"url" json:"url"`
	Desc       string `bson:"desc"  json:"desc"`
	Amount     int    `bson:"amount"` //其他数字统计
}

func (MsgBasic) CollectionName() string {
	return "message_basic"
}

func InsertOneMsg(mb *MsgBasic) error {
	_, err := MongoDB.Collection(MsgBasic{}.CollectionName()).
		InsertOne(context.Background(), mb)
	return err
}

func GetMessageListByRoomId(RoomId string, startTime int64, limit, skip *int64) ([]*MsgBasic, error) {
	data := make([]*MsgBasic, 0)
	cursor, err := MongoDB.Collection(MsgBasic{}.CollectionName()).
		Find(context.Background(), bson.M{
			"room_id": RoomId, "created_at": bson.M{"$lt": startTime},
		}, &options.FindOptions{
			Limit: limit,
			Skip:  skip,
			Sort: bson.D{
				{"created_at", -1},
			},
		})
	if err != nil {
		return nil, err
	}
	for cursor.Next(context.Background()) {
		mb := new(MsgBasic)
		err = cursor.Decode(mb)
		if err != nil {
			return nil, err
		}
		data = append(data, mb)
	}
	return data, nil
}
